package com.tool.cn.util;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 * 系统工具类
 * 
 * @author wangzh
 * 2017年7月27日 下午1:59:45
 */
public class OSUtil {
  
	
	/**
	 * 获取主机名
	 */
    public static String getHostName() {  
        if (System.getenv("COMPUTERNAME") != null) {  
            return System.getenv("COMPUTERNAME");  
        } else {  
        	try {  
                return (InetAddress.getLocalHost()).getHostName();  
            } catch (UnknownHostException uhe) {  
                String host = uhe.getMessage();
                if (host != null) {  
                    int colon = host.indexOf(':');  
                    if (colon > 0) {  
                        return host.substring(0, colon);  
                    }  
                }  
                return "UnknownHost";  
            }    
        }  
    }
    
    /**
     * 获取本机ipv6地址
     */
    public static String getIpV6(){
    	try {
			return InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			return "UnknownIp";
		}
    }
    
    
	/**
	 * 读取tomcat配置文件，获取tomcat端口号，默认8080
	 * @return
	 */
	public static String getPort() {
		// 创建saxReader对象  
        SAXReader reader = new SAXReader();  
        // 通过read方法读取一个文件 转换成Document对象  
        Document document = null;
		try {
			document = reader.read(new File(System.getProperty("catalina.home")+File.separator+"conf"+File.separator+"server.xml"));
		} catch (DocumentException e) {
			e.printStackTrace();
		}  
        //获取根节点元素对象  
        Element node = document.getRootElement();
        
        Element server=(Element) node.elements("Service").get(0);
        
        @SuppressWarnings("unchecked")
		List<Element> result=server.elements("Connector");
        for(Element data:result) {
        	String type=data.attribute("protocol").getText();
        	if(type.contains("HTTP")||type.contains("http")) {
        		return data.attribute("port").getText();
        	}
        }
        return "8080";
	}

}
